package com.hxgz.steel.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.*;
import com.hxgz.steel.domain.*;
import com.hxgz.steel.dto.*;
import com.hxgz.steel.service.ProductService;
import com.hxgz.steel.util.BigDecimalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service("productService")
public class ProductServiceImpl implements ProductService {

  @Autowired
  private ProductMapper productMapper;
  @Autowired
  private CategoryMapper categoryMapper;
  @Autowired
  private ProductModelMapper productModelMapper;
  @Autowired
  private MerchantMapper merchantMapper;
  @Autowired
  private AddressMapper addressMapper;
  @Autowired
  private ProductParameterMapper productParameterMapper;
  @Autowired
  private ProductCommentsMapper productCommentsMapper;
  @Autowired
  private OrderItemMapper orderItemMapper;
  @Override
  public ServerResponse productList(Page page, Map<String,Object> paramMap) {
    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize(), page.getOrderBy());
    List<HomeProductDto> productList = productMapper.productListList(paramMap);
    PageInfo pageinfo = new PageInfo(productList);
    return ServerResponse.createBySuccess(pageinfo);
  }

  /**
   * 查询商品下所有子类
   * @param cateSet
   * @param categoryId
   * @return
   */
  public Set<Category> findCategoryIds(Set<Category> cateSet, Integer categoryId) {
    Category category = categoryMapper.selectByPrimaryKey(categoryId);
    if (category != null) {
      cateSet.add(category);
    }
    List<Category> cateList = categoryMapper.queryCategoryByParentId(categoryId);
    cateList.forEach(cateInfo -> findCategoryIds(
        cateSet, cateInfo.getId()));
    return cateSet;
  }

  public ServerResponse categoryList() {
    //递归查询类别和其下子类别
    Set<Category> cateSet = new HashSet<Category>();
    //findCategoryIds(cateSet);
    List<Category> categoryList = new ArrayList<Category>();
    cateSet.forEach(category -> categoryList.add(category));
    return ServerResponse.createBySuccess(categoryList);
  }

  @Override
  public ServerResponse hotProduct(Page page) {
    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
    List<Product> productList = productMapper.hotProduct();
    PageInfo pageInfo = new PageInfo(productList);
    return ServerResponse.createBySuccess(pageInfo);
  }
  @Override
  public ServerResponse productInfo(Long id) {
        //商品详情
        Product productWithBLOBs = productMapper.getProductAndPriceById(id);
        return ServerResponse.createBySuccess(productWithBLOBs);
  }
  @Override
  public ServerResponse getPriceByKind(Long productId, String model, String color,
                                                   Integer count) {
//    if("".equals(model) ||"".equals(color)||model==null||color==null){
//      return  ServerResponse.createByError();
//    }
      Map map = Maps.newHashMap();
      Map<String,Object> resultMap = new HashMap<>();
      map.put("productId", productId);
      map.put("model", model);
      map.put("color", color);
      BigDecimal totalPrice = new BigDecimal(0);
      List<ProductModel> priceByKind = productModelMapper.getPriceByKind(map);
      Product product = productMapper.getProductById(productId);
      if (product.getFreight() == null || "".equals(product.getFreight())) {
          product.setFreight(new BigDecimal(0));
      }
      if (product.getTaxPoint() == null || "".equals(product.getTaxPoint())) {
          product.setTaxPoint(new BigDecimal("0"));
      }
      if (priceByKind.size() > 0) {
          //单价
          BigDecimal price = priceByKind.get(0).getPrice();
          //总价=单价*数量
          BigDecimal total = BigDecimalUtil.mul(price.doubleValue(), count.doubleValue());
          //税费=总价*税点
          BigDecimal taxation;
          if (Double.valueOf(product.getTaxPoint().toString()) > 0) {
              taxation = BigDecimalUtil.mul(total.doubleValue(), product.getTaxPoint().doubleValue());
          } else {
              taxation = new BigDecimal("0");
          }
          /*
           * 总运费根据运费状态去判断 是一个商品一个运费 还是一种商品一个运费
           * 如果是一个商品一个运费:总运费=单件的运费*数量
           * 如果是一种商品一个运费:总运费 = 单件的运费
           */
          BigDecimal totalFreight;
          if (new Integer(0).equals(product.getFreightStatus())) {
              if (Double.valueOf(product.getFreight().toString()) > 0) {
                  totalFreight = BigDecimalUtil.mul(product.getFreight().doubleValue(), count.doubleValue());
              } else {
                  totalFreight = new BigDecimal("0");
              }
          } else {
              if (Double.valueOf(product.getFreight().toString()) > 0) {
                  totalFreight = product.getFreight();
              } else {
                  totalFreight = new BigDecimal("0");
              }
          }
          //总报价=总价+总运费+税费;
//      1) 总价+总运费
          BigDecimal totalPrice1 = BigDecimalUtil.add(total.doubleValue(), totalFreight.doubleValue());
//      2) 总价+税费
          totalPrice = BigDecimalUtil.add(totalPrice1.doubleValue(), taxation.doubleValue());
          resultMap.put("totalPrice",totalPrice);
          resultMap.put("totalFreight",totalFreight.doubleValue());
      }
      return ServerResponse.createBySuccess(resultMap);
  }

  @Override
  public ServerResponse<ProductStoreDto> getStoreByProduct(Long merchantId) {
    ProductStoreDto psList = merchantMapper.getStoreByProduct(merchantId);
      String businessScope = psList.getBusinessScope();
      if(StringUtils.isNotBlank(businessScope)){
          String[] split = businessScope.split("-");
          StringBuffer buffer = new StringBuffer();
          for (String str : split) {
              switch (Integer.valueOf(str)){
                  case 1:buffer.append("风类 ");
                      break;
                  case 2:buffer.append("水类 ");
                      break;
                  case 3:buffer.append("电类 ");
                      break;
                  case 4:buffer.append("消防类 ");
                      break;
              }
          }
          psList.setBusinessScope(buffer.toString());
      }
      //商品数
      Integer productCount= productMapper.getProductCountByMerchantId(merchantId);
      //销量
      Integer salesCount=orderItemMapper.getBySalesCountMerchantId(merchantId);
      psList.setProductCount(productCount);
      psList.setSalesCount(salesCount);
    return ServerResponse.createBySuccess(psList);
  }

  @Override
  public ServerResponse buyNow(Long userId) {
    Address address = addressMapper.getDefuAddress(userId);
    return ServerResponse.createBySuccess(address);
  }
  @Override
  public ServerResponse storeProdectList(Long id, Page page) {
    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize(), page.getOrderBy());
    List<HomeProductDto> homeProductDtos = productMapper.storeProdectList(id);
    PageInfo pageinfo = new PageInfo(homeProductDtos);
    return ServerResponse.createBySuccess(pageinfo);
  }
  @Override
  public ServerResponse
    productParams(Long id) {
    List<ProductParameter> productParameters = productParameterMapper.listParameterByProId(id);
    return ServerResponse.createBySuccess(productParameters);
  }
  @Override
  public ServerResponse productComments(Long id, Page page) {
    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
    List<ProductCommentsDto> productCommentsDtos = productCommentsMapper.prodectComments(id);
    PageInfo pageInfo = new PageInfo(productCommentsDtos);
    return ServerResponse.createBySuccess(pageInfo);
  }
  @Override
  public ServerResponse getProductType(Long id){
    Map<String ,Object> map = Maps.newHashMap();
//    List<String> modelList= productModelMapper.getTpyeList(id,0);
//    List<String> colorList= productModelMapper.getTpyeList(id,1);
//    map.put("modelList",modelList);
//    map.put("colorList",colorList);
    List<ProductInfoDto> infos = productModelMapper.getTypeInfo(id);
    List<ProductTypeAndColor> types = productModelMapper.getType(id);
    Double minPrice=0.00;
    int i=0;
    ArrayList<ProductInfoDto> list = new ArrayList<>();
    for (ProductTypeAndColor type : types) {
      for (ProductInfoDto info : infos) {
        if(info.getModel().equals(type.getType())){
            list.add(info);
        }
        Double aDouble = Double.valueOf(infos.get(i).getPrice());
        if(i==0){
          minPrice = Double.valueOf(infos.get(i).getPrice());
        }else {
          if(aDouble<minPrice){
            minPrice=aDouble;
          }
        }
          i++;
      }
      i=0;
      ArrayList<ProductInfoDto> colors = new ArrayList<>(list);
      type.setColors(colors);
      type.setMinPrice(minPrice.toString());
      list.removeAll(list);
    }

    return ServerResponse.createBySuccess(types);
  }

  /**
   * 首页面商品列表的搜索按钮
   * @param page
   * @param paramMap
   * @return
   */
  @Override
  public ServerResponse searchProductList(Page page,Map paramMap){
    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
    List<HomeProductDto> HomeProductDto =productMapper.searchProductList(paramMap);
    PageInfo pageInfo = new PageInfo(HomeProductDto);
    return ServerResponse.createBySuccess(pageInfo);
  }

    @Override
    public Long getUserIdByProductId(Long productId) {
        Long userId=productMapper.getUserIdByProductId(productId);
        return userId;
    }

}
